package cn.maxxieyi.aichatbot.holder;

import cn.hutool.core.util.StrUtil;
import cn.maxxieyi.aichatbot.dto.AiChatRequest;
import cn.maxxieyi.aichatbot.dto.AiChatResponse;
import cn.maxxieyi.aichatbot.service.AiApiService;
import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.beans.RecommendInfo;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 简单示例程序，收到文本信息自动回复原信息，收到图片、语音、小视频后根据路径自动保存
 */
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ItchatGmoreAiMsgHander implements IMsgHandlerFace {

    private AiApiService aiApiService;

    private String aiApiKey;

    @Override
    public String textMsgHandle(BaseMsg msg) {

        log.info("收到文本消息"+ JSON.toJSONString(msg));
        String text = msg.getText();
        if (StrUtil.isBlank(text)) {
            return null;
        }
        Boolean isMentioned = false;
        Boolean isSingle = false;
        //群消息发送者昵称
        String senderGroupNickName = null;
        String senderId = msg.getFromGroupUser();
        if (msg.isGroupMsg()) { // 是否群消息
            //是否@我的消息
            String grouopId = msg.getFromUserName();
            //机器人的群昵称
            String groupNickName =null;
            JSONArray groupMemberList = Core.getInstance().getGroupMemeberMap().get(grouopId);
            log.info("群成员：{}",groupMemberList);
            if(groupMemberList!=null) {
                for (int i = 0; i < groupMemberList.size(); i++) {
                    JSONObject groupMember = groupMemberList.getJSONObject(i);
                    String displayName = groupMember.getString("DisplayName");
                    if (groupMember.getString("UserName").equals(Core.getInstance().getUserName())) {
                        groupNickName = displayName;
                    } else if (groupMember.getString("UserName").equals(senderId)) {
                        senderGroupNickName = StrUtil.isNotBlank(displayName) ? displayName : groupMember.getString("NickName");
                    }
                }
            }
            if(groupMemberList==null || senderGroupNickName == null){
                WechatTools.updateWxGroupMemeber(grouopId);
                groupMemberList = Core.getInstance().getGroupMemeberMap().get(grouopId);
                if(groupMemberList==null){
                    for (int i = 0; i < groupMemberList.size(); i++) {
                        JSONObject groupMember = groupMemberList.getJSONObject(i);
                        String displayName = groupMember.getString("DisplayName");
                        if (groupMember.getString("UserName").equals(Core.getInstance().getUserName())) {
                            groupNickName = displayName;
                        } else if (groupMember.getString("UserName").equals(senderId)) {
                            senderGroupNickName = StrUtil.isNotBlank(displayName) ? displayName : groupMember.getString("NickName");
                        }
                    }
                }
            }
            isMentioned = StrUtil.contains(text, "@" + Core.getInstance().getNickName()) || (StrUtil.isNotBlank(groupNickName) && StrUtil.contains(text, "@" + groupNickName));


        }else{
            isSingle = true;
        }
        String replyMsg = null;
        if (isMentioned || isSingle) {
            JSONObject params = new JSONObject();
            //过滤掉@机器人
            params.put("content",text.replaceAll("@[\\w\\u4e00-\\u9fa5]+", ""));
            params.put("aiApiKey",aiApiKey);
            AiChatRequest aiChatRequest = aiApiService.buildChatRequest(params);

            log.info("AI消息发送："+ params.getString("content"));
            AiChatResponse aiChatResponse = aiApiService.chatText(aiChatRequest);
            log.info("AI消息答复：{}",  JSON.toJSONString(aiChatResponse));
            String replyContent = aiChatResponse.getReplyContent();
            if (aiChatResponse.getSuccess() && StrUtil.isNotBlank(replyContent)) {
                //答复消息
                if(isMentioned && StrUtil.isNotBlank(senderGroupNickName)){
                    replyMsg = "@"+ senderGroupNickName +"\u2005\u0020"+replyContent;
                }else {
                    replyMsg = replyContent;
                }
            }
            log.info("回复内容：{}",replyContent);
//            MessageTools.sendMsgByNickName(groupSenderNickName, replyContent);
        }
        return replyMsg;
    }


    @Override
    public String picMsgHandle(BaseMsg msg) {
       /* String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());// 这里使用收到图片的时间作为文件名
        String picPath = "D://itchat4j/pic" + File.separator + fileName + ".jpg"; // 调用此方法来保存图片
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath); // 保存图片的路径*/
        this.log.info("收到图片消息");
        return "收到图片信息";
    }

    @Override
    public String voiceMsgHandle(BaseMsg msg) {
       /* String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String voicePath = "D://itchat4j/voice" + File.separator + fileName + ".mp3";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath);*/
        this.log.info("收到声音消息");
        return "收到声音消息";
    }

    @Override
    public String viedoMsgHandle(BaseMsg msg) {
       /* String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String viedoPath = "D://itchat4j/viedo" + File.separator + fileName + ".mp4";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath);*/
        this.log.info("收到视频消息");
        return "收到视频消息";
    }

    @Override
    public String nameCardMsgHandle(BaseMsg msg) {
        this.log.info("收到名片消息");
        return "收到名片消息";
    }

    @Override
    public void sysMsgHandle(BaseMsg msg) { // 收到系统消息
        String text = msg.getContent();
        this.log.info("收到系统消息:"+text);
    }

    @Override
    public String verifyAddFriendMsgHandle(BaseMsg msg) {
        MessageTools.addFriend(msg, true); // 同意好友请求，false为不接受好友请求
        RecommendInfo recommendInfo = msg.getRecommendInfo();
        String nickName = recommendInfo.getNickName();
        String province = recommendInfo.getProvince();
        String city = recommendInfo.getCity();
        String text = "你好，来自" + province + city + "的" + nickName + "， 欢迎添加我为好友！";
        return text;
    }

    @Override
    public String mediaMsgHandle(BaseMsg msg) {
      String fileName = msg.getFileName();
      /*    String filePath = "D://itchat4j/file" + File.separator + fileName; // 这里是需要保存收到的文件路径，文件可以是任何格式如PDF，WORD，EXCEL等。
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.MEDIA.getType(), filePath);*/
        this.log.info("收到文件消息:"+fileName);
        return "收到文件" + fileName ;
    }

}
